import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:test2/base/base_page.dart';
import 'package:test2/item/item_map.dart';
import 'package:test2/model/map.dart';
import 'package:test2/util/bus.dart';
import 'package:test2/view/map_add.dart';
import 'package:test2/view/scene_list.dart';

class MapList extends StatefulWidget {
  const MapList({super.key, required this.boxName, required this.gameName});

  final String boxName;
  final String gameName;

  @override
  State<MapList> createState() => _MapListState();
}

class _MapListState extends BaseState<MapList> {
  late Box<MapC> box;
  List<MapC> dataList = [];

  @override
  void initState() {
    init();
    bus.on(EventType.map, onDataChange);
    super.initState();
  }

  onDataChange(arg) {
    updateList();
  }

  @override
  void dispose() {
    bus.off(EventType.map, onDataChange);
    box.close();
    super.dispose();
  }

  void init() async {
    box = await Hive.openBox<MapC>(widget.boxName);
    updateList();
  }

  void updateList() {
    setState(() {
      dataList.clear();
      dataList.addAll(box.values);
      dataList = dataList.reversed.toList();

      // 置顶
      final topList = dataList.where((item) => item.top).toList();
      final normalList = dataList.where((item) => !item.top).toList();

      dataList = [...topList, ...normalList];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.gameName)),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          addData();
        },
        child: Icon(Icons.add),
      ),
      body: SizedBox.expand(
        child: Column(
          children: [
            Expanded(
              child: ListView.separated(
                padding: EdgeInsets.only(
                  left: 16,
                  right: 16,
                  top: 16,
                  bottom: 100,
                ),
                itemBuilder: (context, index) {
                  var item = dataList[index];
                  return GestureDetector(
                    onTap: () {
                      itemClick(item);
                    },
                    child: ItemMap(map: item, boxName: widget.boxName),
                  );
                },
                separatorBuilder: (context, index) {
                  return SizedBox(height: 12);
                },
                itemCount: dataList.length,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void itemClick(MapC item) {
    startPage(
      SceneList(boxName: "${widget.boxName}map${item.key}", mapName: item.tip),
    );
  }

  void addData() {
    startPage(MapAdd(boxName: widget.boxName));
  }
}
